from sqlalchemy import select, false
from sqlalchemy.ext.asyncio import AsyncSession

from apps.models import PublicCatalog
from apps.public import schemas
from core.crud import DalBase


class CatalogDal(DalBase):

    def __init__(self, db: AsyncSession):
        super(CatalogDal, self).__init__()
        self.db = db
        self.model = PublicCatalog
        self.schema = schemas.CatalogSimpleOut

    async def get_catalog_tree(self, catalog_type: int, related_id: int = None):
        sql = select(self.model).order_by(self.model.order)
        if catalog_type == 0:
            sql = sql.where(
                self.model.is_delete == false(),
                self.model.catalog_type == 0,
                self.model.related_id == related_id
            )
        queryset = await self.db.scalars(sql)
        datas = list(queryset.all())
        parents = filter(lambda i: not i.parent_id, datas)
        return self.generate_tree_list(datas, parents)

    def generate_tree_list(self, datas: list[PublicCatalog], nodes: filter) -> list:
        """
        生成部门树列表
        :param datas: 总目录列表
        :param nodes: 每层节点目录列表
        :return:
        """
        data = []
        for parent in nodes:
            catalog = schemas.CatalogTreeListOut.model_validate(parent)
            sons = filter(lambda i: i.parent_id == parent.id, datas)
            catalog.children = self.generate_tree_list(datas, sons)
            data.append(catalog.model_dump())
        return data
